package com.bdqn.BookManage.servlet;

import com.bdqn.BookManage.view.BookInfoView;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author : CP
 * @version: 1.0
 * @program : BookManage
 * @description : 修改购买数量
 * @date : 2020-07-28 16:51
 **/
@WebServlet("/amendNum")
public class AmendNumServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();

        String id = req.getParameter("id");
        String type = req.getParameter("type");

        HttpSession session = req.getSession();

        Map<String, BookInfoView> map = (Map<String, BookInfoView>) session.getAttribute("cart");
        BookInfoView bookInfoView = map.get(id);

        if(type.equals("2")){
            if(bookInfoView.getAmount()+1 > bookInfoView.getBookInfo().getStock()){
                out.print("<script>alert('商品库存不足!');location.href='shoppingTrolley.jsp';</script>");
                out.flush();
                out.close();
            }else{
                bookInfoView.setAmount(bookInfoView.getAmount()+1);
            }
        }else if(type.equals("1")){
            if (bookInfoView.getAmount()-1 < 1){
                out.print("<script>alert('至少购买一件商品!');location.href='shoppingTrolley.jsp';</script>");
                out.flush();
                out.close();
            }else {
                bookInfoView.setAmount(bookInfoView.getAmount()-1);
            }
        }

        map.put(id,bookInfoView);
        session.setAttribute("cart",map);
        resp.sendRedirect("shoppingTrolley.jsp");
    }
}
